<template>
    <div class="login-container">
        <div class="login-content">
            <div class="login-title">
                <h2 class="title">LOGIN</h2>
            </div>
            <div class="login-form">
                <el-input v-model="loginInfo.username" placeholder="请输入用户名" :prefix-icon="User" />
                <el-input v-model="loginInfo.password" type="password" placeholder="请输入密码" :prefix-icon="Lock" />
                <el-button type="primary" @click="handleLogin">登录</el-button>
                <div class="login-other">
                    <el-button link type="primary" @click="registerModalVisible = true">立即注册</el-button>
                </div>
            </div>
        </div>
    </div>
    <!-- 注册弹窗 -->
    <el-dialog 
        v-model="registerModalVisible" 
        width="90%" 
        class="register-dialog"
        :before-close="active = 0"
        align-center
        :style="{ height: '80%' }"
    >
        <div class="register-container">
            <el-steps :active="active" style="width: 50%">
                <el-step title="机构信息" />
                <el-step title="完成" />
            </el-steps>
            <div class="register-form-two" v-show="active === 0">
                <AgencyRegister :dialogForm="registerInfo" />
            </div>
            <div class="register-form-one" v-show="active === 1">
                <el-result
                    :icon="registerStatus ? 'success' : 'error'"
                    :title="registerStatus ? '注册成功！' : '注册失败！'"
                    :sub-title="registerStatus ? '恭喜您成为本平台的合作伙伴！' : '请检查填写信息是否正确！'"
                />
            </div>
        </div>
        <template #footer>
            <el-button @click="active --" :disabled="active === 0">上一步</el-button>
            <el-button type="primary" @click="handleRegister()">{{ active === 0 ? '下一步' : '完成' }}</el-button>
        </template>
    </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { User, Lock, Plus, UploadFilled } from '@element-plus/icons-vue'
import { dayjs, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import type { FormInstance, FormRules } from 'element-plus'
import AgencyRegister from '../../components/pc/AgencyRegister.vue';
import { adminApi, agencyApi } from '../../api/app';

/** 登录信息 */
const loginInfo = ref({
    username: '',
    password: ''
});
/** 注册弹窗可见性 */
const registerModalVisible = ref(false);
/** 注册步骤 */
const active = ref(0);
/** 注册信息 */
const registerInfo = ref({
    agencyId: null,
    agencyName: null,
    agencyLogo: null,
    agencyEmail: null,
    agencyPhone: null,
    agencyStartTime: null,
    agencyWebsite: null,
    agencyFax: null,
    agencyIntroduction: null,
    registrationAdministrationAuthority: null,
    registrationCertificateType: null,
    registrationCertificatePhoto: null,
    registrationCertificateAddress: null,
    socialCreditCode: null,
    organizationRating: null,
    agencyNature: null,
    staffsNumber: null,
    volunteersNumber: null,
    corporateName: null,
    corporateId: null,
    bussinessScope: null,
    certificateTimes: null,
    agencyAddress: null,
    agencyPassword: null,
    orgLegalIdCardIsLongTerm: false, // 证书有效期是否长期
    address: [], // 地址
});
/** 注册状态 */
const registerStatus = ref(false);

const router = useRouter();
/** 登录 */
const handleLogin = () => {
    // 如果是管理员 跳转到管理员界面
    if (loginInfo.value.username === 'admin' && loginInfo.value.password === '111111') {
        localStorage.setItem('user', JSON.stringify({ role: 'admin', agencyName: 'admin' })); // 管理员就存角色即可
        router.push('/adminMain/userManage');
        ElMessage.success('登录成功！');
    } else {
        // 否则跳转到募捐机构界面
        agencyApi.toLogin({
            agencyPhone: loginInfo.value.username,
            agencyPassword: loginInfo.value.password
        }).then(res => {
            if (res) {
                localStorage.setItem('user', JSON.stringify({ role: 'agency', ...res }));
                router.push('/adminMain/agencyProjectsManage')
                ElMessage.success('登录成功！');
            } else {
                ElMessage.error('用户名或密码错误！');
                return;
            }
        })
    }
};

/** 注册 */
const handleRegister = () => {
    if (active.value === 0) {
        if (!registerInfo.value.agencyPhone || registerInfo.value.agencyPhone === '' || !registerInfo.value.agencyPassword || registerInfo.value.agencyPassword === '') {
            registerStatus.value = false;
        } else {
            // 处理地址存储格式
            const registrationCertificateAddress = registerInfo.value.address.join('/') + '/' + registerInfo.value.registrationCertificateAddress;
            // 处理时间格式
            let certificateTimes: string;
            // 长期有效，直接转换，短期有效，拼接
            if (registerInfo.value.orgLegalIdCardIsLongTerm) {
                certificateTimes = dayjs(registerInfo.value.certificateTimes).format('YYYY-MM-DD');
            } else {
                certificateTimes = dayjs(registerInfo.value.certificateTimes?.[0]).format('YYYY-MM-DD') + '~' + dayjs(registerInfo.value.certificateTimes?.[1]).format('YYYY-MM-DD');
            }
            const agency = {
                ...registerInfo.value,
                address: null,
                registrationCertificateAddress: registrationCertificateAddress,
                orgLegalIdCardIsLongTerm: undefined,
                certificateTimes: certificateTimes,
                organizationRating: (registerInfo.value.organizationRating || []).join('/'),
                agencyStartTime: dayjs(registerInfo.value.agencyStartTime).format('YYYY-MM-DD')
            }
            adminApi.addAgency(agency).then(res => {
                if (res) {
                    registerStatus.value = true;
                } else {
                    registerStatus.value = false;
                }
            })
        }
        active.value ++;
    } else {
        registerModalVisible.value = false;
        active.value  = 0;
    }
}
</script>

<style lang="less">
.login-container {
    width: 100vw;
    height: 100vh;
    background: url('../../assets/images/admin/360f7dbcb1c9c1c39f67d7cd1ab6cb0b.jpg');
    background-size: cover;

    .login-content {
        background: rgba(255, 255, 255, 0.85);
        position: absolute;
        top: 25%;
        right: 15%;
        width: 400px;
        height: 300px;
        border-radius: 10px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
        padding: 20px;
        align-content: center;

        .login-title {
            display: flex;
            justify-content: center;
            align-content: center;

            .title {
                color: #3c89d4;
            }
        }

        .login-form {
            text-align: center;
            display: flex;
            flex-direction: column;
            gap: 15px;

            .login-other {
                display: flex;
                flex-direction: row-reverse;
            }
        }
    }
}
.register-dialog {
    .el-dialog__body {
        height: 85%;
    }
    .register-container {
        display: flex;
        width: 100%;
        height: 100%;
        flex-direction: column;
        justify-content: center;
        align-items: center;

        .register-form-one {
            margin-top: 50px;
        }

        .register-form-two {
            width: 100%;
            max-height: 100%;
            overflow-y: auto;

            .title {
                font-size: 15px;
                font-weight: bold;
                border-left: #3c89d4 5px solid;
                padding-left: 5px;
            }

            .form-content {
                margin-top: 10px;

                .avatar-uploader {
                    width: 100px;
                    height: 100px;
                    display: block;
                    border: 1px dashed gray;
                    border-radius: 6px;
                    cursor: pointer;
                    position: relative;
                    overflow: hidden;
                    transition: var(--el-transition-duration-fast); 

                    .el-icon.avatar-uploader-icon {
                        font-size: 28px;
                        color: #8c939d;
                        width: 100px;
                        height: 100px;
                        text-align: center;
                    }
                }

                .avatar-uploader:hover {
                    border-color: var(--el-color-primary);
                }

                .el-input, .el-select {
                    width: 220px;
                }

                .date-range {
                    margin-left: 10px;
                }

                .el-switch__label.is-active {
                    color: var(--el-text-color-primary);
                }

                .el-switch__label {
                    color: var(--el-color-primary)
                }

                .el-upload-dragger {
                    height: 50px;
                    background-color: gainsboro;
                    display: flex;
                    align-items: center;
                }
            }
        }
    }

    .el-button {
        width: 100px;
    }
}
</style>